import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import './index.less';
import { Carousel, Card, List, WhiteSpace, Flex, Modal, Stepper, ListView } from "antd-mobile";
import { Row, Icon, Button, Col, Rate, Avatar, message } from "antd";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/app/util-tool";
import moment from "moment";
// import { any } from "prop-types";
const Item = List.Item;
const Brief = Item.Brief;
// const RadioItem = Radio.RadioItem;

function MyBody(props: any) {
    return (
        <div className="am-list-body my-body" style={{ height: '100%' }}>
            {props.children}
        </div>
    );
}
/**
 * 组件：服务详情视图控件状态
 */
export interface ServiceInfoViewState extends ReactViewState {
    /** 数据 */
    data?: any[];
    /** 图片高度 */
    imgHeight?: number | string;
    /** 底部弹框 */
    modal?: boolean;
    /** 基础数据 */
    base_data?: object;
    /** 提交表单 */
    formValues?: {};
    /** 总计金额 */
    count_amount?: number;
    /** 服务数量 */
    service_count?: number;
    /** 评论列表 */
    comment_list?: any[];
    /** 长列表数据 */
    dataSource?: any;
    /** 长列表容器高度 */
    height?: any;
}
/**
 * 组件：服务详情视图控件
 */
export class ServiceInfoView extends ReactView<ServiceInfoViewControl, ServiceInfoViewState> {
    constructor(props: any) {
        super(props);
        const ds = new ListView.DataSource({
            rowHasChanged: (r1: any, r2: any) => r1 !== r2
        });
        this.state = {
            data: [],
            imgHeight: 176,
            modal: false,
            base_data: {},
            formValues: {},
            count_amount: 0,
            service_count: 1,
            comment_list: [],
            dataSource: ds,
            height: document.documentElement!.clientHeight,
        };
    }
    onClose = () => {
        this.setState({
            modal: false,
        });
    }
    pay = () => {
        // this.setState({
        //     modal: true,
        // });
        let parms = JSON.stringify(this.state.formValues);
        console.warn('111', parms);
        this.props.history!.push(ROUTE_PATH.confirmOrders + '/' + parms);
    }
    ok = () => {
        // this.setState({
        //     modal: false,
        // });
        let parms = JSON.stringify(this.state.formValues);
        console.warn('111', parms);
        this.props.history!.push(ROUTE_PATH.confirmOrders + '/' + parms);
    }
    componentDidMount() {

        AppServiceUtility.service_detail_service.get_service_product_package_detail!({ id: this.props.match!.params.key }, 1, 1)!
            .then((data: any) => {
                console.warn('000', data);
                let service_product = {};
                service_product['service_product_id'] = this.props.match!.params.key;
                let product_list: any[] = [];
                if (data) {
                    console.warn('1111', data[0]);
                    data[0].item_list.map((item: any, index: number) => {
                        console.info('0.0.0.0',item);
                        let s_item = {};
                        let option_list: any[] = [];
                        s_item['item_name'] = item.item_name;
                        s_item['item_price'] = item.item_price;
                        item.item_option_list.map((value: any, i: number) => {
                            let opton_dict = {};
                            opton_dict['name'] = value.name;
                            opton_dict['option_value'] = value.default_value;
                            option_list.push(opton_dict);
                        });
                        s_item['service_option'] = option_list;
                        // for (let opt in item.item_option_list) {
                        //     if (opt) {
                        //         console.log(opt);
                        //         // s_item['item_price'] = item.item_option_list[opt].item_price;
                        //         s_item['option_value'] = parseInt(item.item_option_list[opt].option_value, undefined);
                        //         s_item['option_name'] = parseInt(item.item_option_list[opt].option_name, undefined);
                        //         // if (item.item_option_list[opt] === parseInt(item.value, undefined)) {
                        //         //     s_item['key'] = opt;
                        //         //     s_item['value'] = parseInt(item.value, undefined);
                        //         // }
                        //     }
                        // }
                        product_list.push(s_item);
                    });
                }
                service_product['item_list'] = product_list;
                service_product['count'] = 1;
                service_product['name'] = data[0].name;
                service_product['total_price'] = data[0].total_price * service_product['count'];
                // service_product['introduce'] = data[0].introduce;
                this.setState({
                    base_data: data[0],
                    formValues: service_product,
                    count_amount: data[0]['total_price'],
                });
                // service_product['total_price'] = data[0].total_price;
            })
            .catch((err) => {
                console.info(err);
            });
        let id = this.props.match!.params.key;
        console.warn(id);
        AppServiceUtility.comment_service.get_comment_list_all!({ 'comment_object_id': id })!
            .then((data: any) => {
                let comment_list: any[] = [];
                if (data) {
                    comment_list = data.result.map((key: any, value: any) => {
                        let comment = {};
                        comment['id'] = key['id'];
                        comment['content'] = key['content'];
                        comment['comment_date'] = key['comment_date'];
                        comment['like_list'] = key.like_list;
                        comment['comment_user'] = key['comment_user'];
                        return comment;
                    });
                    console.info(comment_list);
                    this.setState(
                        { comment_list }
                    );
                }
            });

    }
    onChange = (key: any, value: any, index: number) => {
        let { formValues, count_amount, service_count } = this.state;
        count_amount = 0;
        formValues!['item_list'][index]['name'] = key;
        formValues!['item_list'][index]['option_value'] = value;
        formValues!['item_list'].map((value: any, index: number) => {
            count_amount += value.total_price;
        });
        count_amount = count_amount * service_count!;
        // console.warn(formValues);
        this.setState({
            formValues,
            count_amount
        });
    }
    getEle = (index: number) => {
        let ele: any[] = [];
        let obj: any;
        obj = this.state.base_data!['item_list'][index]['item_option_list'];
        for (let option in this.state.base_data!['item_list'][index]['item_option_list']) {
            if (option) {
                console.warn(this.state.base_data!['item_list'][index]['item_option_list']);
                ele.push(
                    <Item extra={obj[option]['option_value']}>{obj[option]['name']}</Item>
                    // <RadioItem key={option} checked={this.state.formValues!['item_list']![0]['item_option_list'] ? option === this.state.formValues!['item_list']![0]['item_option_list'][index]['option_name'] : false} onChange={() => this.onChange(option, obj[option], index)}>
                    //     {option}
                    // </RadioItem>
                );
            }
        }
        return ele;
    }
    /** 服务数量 */
    countChage = (value: any) => {
        let { formValues } = this.state;
        formValues!['count'] = value;
        let count_amount = 0;
        console.warn(formValues);
        formValues!['item_list'].map((value: any, index: number) => {
            count_amount += value.item_price;
            console.warn(formValues!['item_list']);
        });
        count_amount = count_amount * value;
        this.setState({
            service_count: value,
            formValues,
            count_amount,
        });
    }
    onClickRow = (id: string) => {
        console.info(id);
        this.props.history!.push(ROUTE_PATH.childCommmentList + '/' + id);
    }
    /** 加入购物车按钮 */
    add_to_cart = () => {
        let storage = window.localStorage;
        if (storage.getItem('shop')) {
            let shop_str = storage.getItem('shop');
            let shop_list: any[] = shop_str!.split('___');
            shop_list.push(JSON.stringify(this.state.formValues!));
            let shop = shop_list.join('___');
            storage.setItem('shop', shop);
        } else {
            let shop_str = JSON.stringify(this.state.formValues!);
            let shop_list = [];
            shop_list.push(shop_str);
            let shop = shop_list.join('___');
            storage.setItem('shop', shop);
        }
        message.info('添加购物车成功。');
    }
    shop = () => {
        this.props.history!.push(ROUTE_PATH.confirmOrders);
    }
    render() {
        let { comment_list, dataSource } = this.state;
        // let id = this.props.match!.params.key;
        // let type = this.props.match!.params.code;
        const comment = (owData: any, sectionID: any, rowID: any) => {
            return (
                <div>
                    <Card>
                        <Row type='flex' justify='center' >
                            <Col className='list-col' span={3}><WhiteSpace size='sm' /><Avatar size='large' icon="user" /></Col>
                            <Col span={20} className='list-col'>
                                <WhiteSpace size='sm' />
                                <Row>
                                    <Col span={12}><strong>{owData.comment_user}</strong></Col>
                                    <Col span={12}>{moment(owData.comment_date).format("YYYY-MM-DD hh:mm")}</Col>
                                </Row>
                                <Row>
                                    {owData.content}
                                </Row>
                            </Col>
                        </Row>
                    </Card>
                </div>
            );
        };
        return (
            <div>
                <Carousel
                    autoplay={true}
                    infinite={true}
                >
                    {this.state.data!.map((item: any, index: number) => {
                        return (
                            <a
                                className='carousel-a'
                                key={index}
                                href="javascript:;"
                                style={{ height: this.state.imgHeight }}
                            >
                                <img
                                    className='carousel-img'
                                    src={item}
                                    alt=""
                                    onLoad={() => {
                                        window.dispatchEvent(new Event('resize'));
                                        this.setState({ imgHeight: 'auto' });
                                    }}
                                />
                            </a>
                        );
                    })}
                </Carousel>
                <Card className='info-card'>
                    <Row><strong>{this.state.base_data ? this.state.base_data['name'] : ''}</strong></Row>
                    <Row>
                        {/* <Col span={12}>{this.state.base_data ? this.state.base_data['introduce'] : ''}</Col> */}
                        <Col span={10}>{this.state.base_data ? this.state.base_data['pay_count'] : 0}人已下单</Col>
                    </Row>
                </Card>
                <WhiteSpace size="lg" />
                <List>
                    <Item
                        arrow={undefined}
                        multipleLine={true}
                        extra={<Icon className='item-icon-size' type="phone" theme="filled" />}
                        wrap={true}
                    >
                        {this.state.base_data!['org_name'] ? this.state.base_data!['org_name'] : ''}
                        <Brief><Rate character={<Icon type="heart" theme="filled" />} allowHalf={true} disabled={true} value={this.state.base_data!['org_level'] ? this.state.base_data!['org_level'] : 0} />{this.state.base_data!['org_level']}分</Brief>
                        <Brief>{this.state.base_data!['org_address'] ? this.state.base_data!['org_address'] : ''}</Brief>
                    </Item>
                </List>
                <WhiteSpace size="lg" />
                <Card>
                    <Card.Header
                        title={
                            <Row>
                                <Col span={12}>服务清单</Col>
                                {/* <Col span={12}>总计服务次数 20</Col> */}
                            </Row>
                        }
                    />
                    <Card.Body>
                        <div>
                            <strong>•{this.state.base_data ? this.state.base_data['name'] : ''}</strong>
                        </div>
                        {
                            this.state.base_data!['item_list'] ? this.state.base_data!['item_list'].map((value: any, index: any) => {
                                return (
                                    <Flex key={value.id}>
                                        <Flex.Item>&nbsp;{value.item_name}</Flex.Item>

                                        {/* {value.item_option_list!.map((option: any, i: any) => {
                                            return(<Flex.Item key={value.id}>{option.option_name}:{option.option_value} </Flex.Item>);
                                            })
                                        } */}

                                    </Flex>
                                );
                            }) : ''
                        }
                        <div>
                            <strong>•产品介绍</strong>
                        </div>
                        <Flex>
                            <Flex.Item>&nbsp;{this.state.base_data ? this.state.base_data['introduce'] : ''}</Flex.Item>
                        </Flex>
                    </Card.Body>
                </Card>
                {/* 没有机构介绍数据 */}
                {/* <WhiteSpace size="lg" />
                <Card>
                    <Card.Header
                        title="机构介绍"
                    />
                    <Card.Body>
                        <div>注：仅限政府资助长者购买</div>
                        <div>【服务时长】每月上门服务3次，每次90分钟</div>
                        <div>【适用人群】社区内长者</div>
                        <div>【政务人员】护理员</div>
                        <div>【服务范围】南海区大沥镇、狮山镇、西樵镇、里水镇、丹灶镇、九江镇、桂城街道</div>
                    </Card.Body>
                </Card> */}

                {/* 没有服务评价数据 */}
                <WhiteSpace size="lg" />
                <Card className='list-conten'>
                    <Card.Header
                        title="服务评价"
                    />
                    <div className='tabs-content'>
                        {
                            comment_list && comment_list.length ?
                                <ListView
                                    ref={el => this['lv'] = el}
                                    dataSource={dataSource.cloneWithRows(comment_list)}
                                    renderRow={comment}
                                    initialListSize={10}
                                    pageSize={10}
                                    renderBodyComponent={() => <MyBody />}
                                    style={{ height: this.state.height }}
                                />
                                :
                                <Row className='tabs-content' type='flex' justify='center'>
                                    暂无评价
                                    </Row>
                        }
                    </div>
                    <WhiteSpace size="lg" />
                    <Card.Footer extra='查看全部评价>' />
                </Card>
                {/* <Card className='list-conten'>
                    <Card.Header
                        title="服务评价"
                    />
                    <Row type='flex' justify='center'>
                        <Col className='list-col' span={3}><WhiteSpace size='sm' /><Avatar size='large' icon="user" /></Col>
                        <Col span={20} className='list-col'>
                            <WhiteSpace size='sm' />
                            <Row>
                                <Col span={12}><strong>陈默默</strong></Col>
                                <Col span={12}>2019-08-13</Col>
                            </Row>
                            <Row><Rate character={<Icon type="heart" theme="filled" />} allowHalf={true} disabled={true} value={4.5} /></Row>
                            <Row>
                                评价内容评价内容评价内容评价内容评价内容评价内容评价内容评价内容评价内容
                            </Row>
                        </Col>
                    </Row>
                    <WhiteSpace size="lg" />
                    <Card.Footer extra='查看全部评价>' />
                </Card> */}
                <WhiteSpace size="lg" />
                <WhiteSpace size="lg" />
                <WhiteSpace size="lg" />
                <List className="confirmation-orders-buttom info-list">
                    <Item extra={<Row gutter={20}><Col span={12}><Button type='primary' onClick={this.add_to_cart}>加入购物车</Button></Col><Col span={12}><Button type='primary' onClick={this.pay}>立即购买</Button></Col></Row>}>
                        <Row type='flex' justify='center'>¥{this.state.base_data!['total_price'] ? this.state.base_data!['total_price'] : 0}</Row>
                    </Item>
                </List>
                <Modal
                    popup={true}
                    visible={this.state.modal!}
                    onClose={this.onClose}
                    animationType="slide-up"
                >
                    <Card>
                        <Card.Header title='服务定制' />
                        <Card.Body>
                            {
                                this.state.base_data!['item_list'] ?
                                    this.state.base_data!['item_list'].map((value: any, index: any) => {
                                        return (
                                            <List key={index} renderHeader={(<strong>{value.item_name}</strong>)}>
                                                {
                                                    this.getEle(index)
                                                }
                                            </List>
                                        );
                                    }) : ''
                            }
                            <List>
                                {/* {data.map(i => (
                                    <CheckboxItem key={i.value}>
                                        {i.label}
                                    </CheckboxItem>
                                ))} */}
                                {/* <Item arrow='empty' multipleLine={true} onClick={() => { }}>
                                    备注
                                <Brief>所有服务在一个月内完成</Brief>
                                </Item> */}
                                <Item arrow='empty'>
                                    数量
                                <Brief><Stepper showNumber={true} defaultValue={this.state.service_count} value={this.state.service_count} onChange={this.countChage} /></Brief>
                                </Item>
                                <Item extra={<Button type='primary' onClick={this.ok}>确定</Button>}>
                                    ¥{this.state.count_amount}
                                </Item>
                            </List>
                        </Card.Body>
                    </Card>
                </Modal>
                <div className='shopping-cart' onClick={this.shop}>
                    <Icon type="shop" />
                </div>
            </div>
        );
    }
}

/**
 * 组件：服务详情视图控件
 * 控制服务详情视图控件
 */
@addon('ServiceInfoView', '服务详情视图控件', '控制服务详情视图控件')
@reactControl(ServiceInfoView, true)
export class ServiceInfoViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}